<template>
  <div v-show="!startUpload" class="uploader-start-panel">
    <VideoUploadStart @addFile="addFile"></VideoUploadStart>
  </div>
  <!-- 上传文件 -->
  <div v-if="startUpload">
    <div class="file-list" v-draggable="[fileList, { animation: 150, handle: '.video-p' }]">
      <div class="file-item" v-for="(item, index) in fileList" :key="index">
        <div class="video-p">
          <div class="iconfont icon-video"></div>
          <div class="video-p-info">P{{ index + 1 }}</div>
        </div>
        <div class="video-info">
          <div class="video-title">
            <div class="upload-info">
              <div class="title">
                <el-input
                  v-show="item.edit"
                  v-model="item.fileName"
                  :id="'file-input' + item.uid"
                  size="small"
                  @blur="editEnd(index)"
                ></el-input>
                <div v-show="!item.edit" class="title-show" @click="editFileName(index)">
                  {{ item.fileName }}
                </div>
              </div>
              <div class="upload-status">
                <span v-if="item.status == 'uploading'">
                  已上传：{{ sizeToStr(item.uploadSize as number) }} /
                  {{ sizeToStr(item.totalSize as number) }}
                </span>
                <span
                  v-else
                  :class="['iconfont', 'icon-' + STATUS[item.status].icon]"
                  :style="{
                    color: STATUS[item.status].color
                  }"
                >
                  {{ STATUS[item.status].desc }}
                </span>
              </div>
            </div>
            <div class="op">
              <div class="item percent" v-if="item.status == 'uploading'">
                {{ item.uploadPercent }} %
              </div>
              <template v-if="item.status == 'uploading'">
                <div
                  v-if="item.pause"
                  class="item iconfont icon-play3"
                  @click="restartUpload(item.uid)"
                ></div>
                <div v-else class="item iconfont icon-pause" @click="pauseUpload(item.uid)"></div>
              </template>
              <div class="item iconfont icon-del" @click="delFile(index)"></div>
            </div>
          </div>
          <div class="video-progress" v-if="item.status == 'uploading' || item.status == 'success'">
            <el-progress
              :percentage="item.uploadPercent"
              :show-text="false"
              :stroke-width="3"
              :status="item.status == 'uploading' ? '' : 'success'"
            ></el-progress>
          </div>
        </div>
      </div>
    </div>
    <div
      class="add-video-btn"
      v-if="fileList.length < (sysSettingStore.sysSetting?.videoPCount || 0)"
    >
      <el-upload multiple :show-file-list="false" :http-request="addFile" :accept="videoAccept">
        <el-button type="primary">添加分P</el-button>
      </el-upload>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref } from 'vue'
import VideoUploadStart from './VideoUploadStart.vue'
import type { UploadRawFile, UploadRequestOptions } from 'element-plus'
import { mitter } from '@/eventbus/eventBus'
import { vDraggable } from 'vue-draggable-plus'
import { getFileName, sizeToStr } from '@/utils/utilsFun'
import { useSysSettingStore } from '@/stores/sysSetting'
import message from '@/utils/message'
import {
  delUploadVideoHttpRequest,
  preUploadVideoHttpRequest,
  uploadVideoHttpRequest
} from '@/services/api/video'

const sysSettingStore = useSysSettingStore()

//上传文件能接受的后缀
const videoAccept = ref('.mp4,.avi,.rmvb,.mkv,.mov')

//分片大小
const CHUNK_SIZE = 1024 * 128
//同时最大上传数量
const MAX_UPLOADING = 3

type StatusItem = {
  icon: string
  value?: string
  desc?: string
  color?: string
}

type FileType = {
  file: UploadRawFile
  edit?: boolean
  fileName: string
  uid: number
  status: string //文件状态
  totalSize: number //文件总大小
  uploadSize: number // 文件上传的大小
  uploadPercent: number //文件上传进度
  pause: boolean //文件是否暂停上传
  uploadId?: string //文件预上传ID
  errorMsg?: string //失败信息
  del?: boolean
  chunkIndex?: number
  fileId?: string
}

const STATUS: Record<string, StatusItem> = {
  emptyfile: {
    icon: 'error'
  },
  largefile: {
    value: 'largefile',
    desc: '文件超过大小' + sysSettingStore.sysSetting?.videoSize + 'MB',
    color: '#F75000',
    icon: 'error'
  },
  waiting: {
    value: 'waiting',
    desc: '等待上传',
    color: '#e6a23c',
    icon: 'waiting'
  },
  uploading: {
    value: 'uploading',
    desc: '上传中',
    color: '#409eff',
    icon: 'upload'
  },
  fail: {
    value: 'fail',
    desc: '上传失败',
    color: '#F75000',
    icon: 'error'
  },
  success: {
    value: 'success',
    desc: '上传完成',
    color: '#67c23a',
    icon: 'success'
  }
}

//是否显示上传文件页面
const startUpload = ref(false)

//文件列表
const fileList = ref<Array<FileType>>([])

//找到当前文件
const getFileByUid = (uid: number): FileType => {
  const currentFile = fileList.value.find((item) => {
    return item.uid == uid
  })
  return currentFile as FileType
}

//添加文件
const addFile = (file: UploadRequestOptions) => {
  // 获取原始文件对象
  const rawFile = file.file as UploadRawFile

  // 检查文件数量限制
  if (fileList.value.length >= (sysSettingStore.sysSetting?.videoCount ?? 0)) {
    message.warning(`最多只能添加${sysSettingStore.sysSetting?.videoCount}个视频`)
  }

  // 获取文件名
  const fileName = getFileName(rawFile.name)

  //开始上传文件
  const fileItem = {
    file: rawFile,
    uid: rawFile.uid,
    fileName,
    status: STATUS.waiting.value as string,
    uploadSize: 0,
    totalSize: rawFile.size,
    uploadPercent: 0,
    pause: false,
    chunkIndex: 0, //文件分片
    errorMsg: undefined
  }
  //把文件添加到列表中
  fileList.value.push(fileItem)
  //文件信息判断
  if (fileItem.totalSize == 0) {
    fileItem.status = STATUS.emptyfile.value as string
    return Promise.resolve()
  }
  //超过规定的最大限制
  if (
    sysSettingStore.sysSetting &&
    fileItem.totalSize > sysSettingStore.sysSetting.videoSize * 1024 * 1024
  ) {
    fileItem.status = STATUS.largefile.value as string
    return Promise.resolve()
  }
  // 检查当前正在上传的文件数量
  let uploadingFiles = fileList.value.filter((item) => {
    return item.status == STATUS.uploading.value
  })
  // 超过最大同时上传数量
  if (uploadingFiles.length > MAX_UPLOADING) {
    return Promise.resolve()
  }
  // 开始上传文件（传入文件UID）
  uploadFile(fileItem.uid)
  console.log(rawFile, '文件信息')
  return Promise.resolve()
}
//上传文件（分片上传）
const uploadFile = async (uid: number, chunkIndex?: number) => {
  // 获取当前文件对象
  const cureentFile = getFileByUid(uid)
  cureentFile.status = STATUS.uploading.value as string // 更新状态为上传中

  // 设置当前分片索引（默认为0）
  chunkIndex = chunkIndex ? chunkIndex : 0

  const file = cureentFile.file
  const fileSize = cureentFile.totalSize // 当前文件总大小
  const chunks = Math.ceil(fileSize / CHUNK_SIZE) // 计算总分片数

  //如果没有预上传文件ID
  if (!cureentFile.uploadId) {
    let resultData = await preUploadVideoHttpRequest(cureentFile.fileName, chunks)
    if (resultData.code != 200) {
      cureentFile.status = STATUS.fail.value as string
      cureentFile.errorMsg = resultData.info
      return
    }

    // 保存预上传ID
    cureentFile.uploadId = resultData.data
  }

  // 分片上传循环
  for (let i = chunkIndex; i < chunks; i++) {
    console.log(i, '@@@')

    //如果当前文件已经暂停或者点击了删除就暂停上传
    if (cureentFile.pause || cureentFile.del) {
      break
    }

    // 计算当前分片的起始和结束位置
    let start = i * CHUNK_SIZE
    let end = start + CHUNK_SIZE >= fileSize ? fileSize : start + CHUNK_SIZE

    // 获取分片数据
    let chunkFile = file.slice(start, end)

    //上传分片视频
    let uploadResult = await uploadVideoHttpRequest(
      {
        chunkFile: chunkFile,
        uploadId: cureentFile.uploadId,
        chunkIndex: i
      },
      {
        progressCallback: (progress) => {
          // 更新进度条显示
          let loaded = progress.loaded
          if (loaded > fileSize) {
            loaded = fileSize
          }
          // 更新上传进度
          cureentFile.uploadSize = i * CHUNK_SIZE + loaded
          cureentFile.uploadPercent = Math.floor((cureentFile.uploadSize / fileSize) * 100)
        },
        errorCallback: (error) => {
          cureentFile.status = STATUS.fail.value as string
          cureentFile.errorMsg = error
        }
      }
    )

    // 上传失败处理
    if (uploadResult.code != 200) {
      return
    }

    // 更新当前分片索引
    cureentFile.chunkIndex = i

    // 如果是最后一个分片
    if (i < chunks - 1) {
      continue
    }

    // 上传完成处理
    cureentFile.status = STATUS.success.value as string
    cureentFile.uploadPercent = 100
    // 自动开始下一个等待中的文件上传
    const nextItem = fileList.value.find((item) => item.status == STATUS.waiting.value)
    if (nextItem) uploadFile(nextItem.uid)
  }
}

//失焦事件
const editEnd = (index: number) => {
  const cureentFile = fileList.value[index]
  cureentFile.edit = false
}
//获取焦点
const editFileName = (index: number) => {
  const cureentFile = fileList.value[index]
  cureentFile.edit = true
  nextTick(() => {
    const input = document.querySelector('#file-input' + cureentFile.uid) as HTMLInputElement
    input?.focus()
  })
}

mitter.on('startUpload', () => {
  startUpload.value = true
  console.log(startUpload.value, '事件')

  fileList.value = []
})

//删除上传好之后的文件   正在上传的文件或已经
const delFile = async (index: number) => {
  //拿到你当前点击的文件
  const cureentFile = fileList.value[index]
  cureentFile.del = true
  fileList.value.splice(index, 1)
  if (cureentFile.fileId) {
    return
  }
  //删除视频文件
  const delRes = await delUploadVideoHttpRequest(cureentFile.uploadId as string)
  console.log(delRes)
}
//继续上传
const restartUpload = (uid: number) => {
  const cureentFile = getFileByUid(uid)
  cureentFile.pause = false
  //重新启动上传
  uploadFile(uid, cureentFile.chunkIndex)
}
//暂停上传
const pauseUpload = (uid: number) => {
  const cureentFile = getFileByUid(uid)
  cureentFile.pause = true
}

// 获取可提交的上传文件列表
const getUploadFileList = () => {
  let failCount = 0 // 统计失败文件数量
  let noUploadCount = 0 // 统计未完成上传文件数量

  // 遍历文件列表进行检查
  for (let i = 0, item; (item = fileList.value[i]), i < fileList.value.length; i++) {
    // 检查失败状态的文件（上传失败或空文件）
    if (item.status == STATUS.fail.value || item.status == STATUS.emptyfile.value) {
      failCount++
      continue
    }

    // 检查未完成状态的文件（正在上传或等待上传）
    if (item.status == STATUS.uploading.value || item.status == STATUS.waiting.value) {
      noUploadCount++
      continue
    }
  }

  // 存在失败文件时的处理
  if (failCount > 0) {
    message.warning('请删除上传失败的文件')
    return null
  }

  // 存在未完成上传文件时的处理
  if (noUploadCount > 0) {
    message.warning('文件还未上传完成无法提交')
    return null
  }

  // 构建可提交的文件列表（只包含必要字段）
  const uploadFileList = fileList.value.map((item) => {
    return {
      uploadId: item.uploadId,
      fileId: item.fileId,
      fileName: item.fileName
    }
  })

  return uploadFileList
}

const initUploader = (_startUpload: boolean, videoList: any) => {
  startUpload.value = _startUpload
  fileList.value.splice(0, fileList.value.length)
  videoList.forEach((item: any) => {
    //如果转码成功
    if (item.transferResult == 1) {
      item.status = STATUS.success.value
    } else {
      item.status = STATUS.fail.value
    }
    item.uid = item.fileId
    item.uploadPercent = 100
    fileList.value.push(item)
  })
}

defineExpose({
  getUploadFileList,
  initUploader
})

onMounted(() => {})

onUnmounted(() => {
  mitter.off('startUpload')
})
</script>

<style lang="less" scoped>
.file-list {
  background-color: #f6f7f8;
  border-radius: 5px;
  margin: 0 200px 0 20px;
  .file-item {
    padding: 10px;
    display: flex;
    margin-bottom: 10px;
    .video-p {
      flex-shrink: 0;
      position: relative;
      width: 44px;
      height: 40px;
      cursor: move;
      .icon-video {
        font-size: 40px;
        color: #a6def1;
        padding: 0;
      }
      .video-p-info {
        width: 35px;
        line-height: 40px;
        text-align: center;
        color: #fff;
        left: 0;
        top: 0;
        z-index: 1;
        position: absolute;
      }
    }
    .video-info {
      flex: 1;
      min-width: 0;
      padding-left: 10px;
      .video-title {
        display: flex;
        width: 100%;
        align-items: center;
        .upload-info {
          width: 100%;
          min-width: 0;
          flex: 1;
          .title {
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            .title-show {
              line-height: 24px;
              padding-left: 7px;
            }
          }
          .upload-status {
            margin-top: 5px;
            color: #999;
            font-size: 12px;
            .iconfont {
              font-size: 12px;
              &::before {
                font-size: 16px;
                margin-right: 2px;
              }
            }
          }
        }
        .op {
          margin-left: 10px;
          display: flex;
          align-items: center;
          color: #909090;
          .item {
            margin-right: 10px;
            font-size: 13px;
          }
          .percent {
            // width: 30px;
          }
          .iconfont {
            cursor: pointer;
            font-size: 20px;
            color: #909090;
          }
        }
      }
      .video-progress {
        margin-top: 5px;
      }
    }
  }
}
.add-video-btn {
  padding-left: 20px;
  margin-bottom: 10px;
}
</style>
